package edu.ntu.cloudroid.server.backendservice;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import java.util.List;

import edu.ntu.cloudroid.model.data.AbstractData;

public class DataCache {
	static Map<DataCacheKey, List<AbstractData>> dataMap = new HashMap<DataCacheKey, List<AbstractData>>();
	static int size = 100;
	static Object lock = new Object();
	static Random rand = new Random(100);
	public static List<AbstractData> getFromCache(String user, Date ts){
		synchronized (lock){
		DataCacheKey dck = new DataCacheKey(user,ts);
		if (dataMap.size()==0)
			return null;
		if (dataMap.containsKey(dck)){
			return dataMap.get(dck);
		}
		else
			return null;
		}
		
	}
	
	public static void purgeCache(){
		dataMap = new HashMap<DataCacheKey, List<AbstractData>>();
	}
	
	public static void updateCache(String user, Date ts, List<AbstractData> data){
		synchronized (lock){
		DataCacheKey dck = new DataCacheKey(user,ts);
		if (dataMap.size()==0)
			dataMap.put(dck, data);
		else{
			if (!dataMap.containsKey(dck)){
				if (dataMap.size()==size){
					//remove a random item
					DataCacheKey removedKey = (DataCacheKey)dataMap.keySet().toArray()[rand.nextInt(size)];
					dataMap.remove(removedKey);
					dataMap.put(dck, data);
				}
				else
					dataMap.put(dck, data);
			}
		}
		}		
	}
}

class DataCacheKey{
	String user;
	Date timestamp;
	public DataCacheKey(String u, Date ts){
		this.user = u;
		this.timestamp = ts;
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((timestamp == null) ? 0 : timestamp.hashCode());
		result = prime * result + ((user == null) ? 0 : user.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		DataCacheKey other = (DataCacheKey) obj;
		if (timestamp == null) {
			if (other.timestamp != null)
				return false;
		} else if (!timestamp.equals(other.timestamp))
			return false;
		if (user == null) {
			if (other.user != null)
				return false;
		} else if (!user.equals(other.user))
			return false;
		return true;
	}
	
}